package com.eatme.web.util.jwt;

import com.eatme.web.common.vo.AppResponse;
import com.eatme.web.security.domain.vo.RefreshTokenRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.nio.file.AccessDeniedException;

@Component
public class JwtServiceImpl {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    NimbusJoseJwtUtil nimbusJoseJwtUtil;

    public AppResponse login(UserDetails userDetails) throws AuthenticationException {
        return AppResponse.ok().data(new RefreshTokenRequest(nimbusJoseJwtUtil.createAccessToken(userDetails), nimbusJoseJwtUtil.createRefreshToken(userDetails)));
    }

//    public AppResponse login(String username,String password) throws AuthenticationException {
//        return securitySysUserDao.findOptionalByUsername(username).filter(user -> passwordEncoder.matches(password,user.getPassword()))
//                .map(user -> AppResponse.ok().data(new Auth(jwtUtil.createAccessToken(user),
//                        jwtUtil.createRefreshToken(user))
//                )).orElseThrow(() ->new BadCredentialsException("用户名或密码错误"));
//
//    }

    public AppResponse refreshToken(String refreshToken) throws AccessDeniedException {
        if (!nimbusJoseJwtUtil.validateToken(refreshToken)) {
            throw new AccessDeniedException("访问被拒绝");
        }
        return AppResponse.ok().data(new RefreshTokenRequest(nimbusJoseJwtUtil.createAccessTokenWithRefreshToken(refreshToken), refreshToken));
    }
}
